﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AMS.DD35.WebMVC3.Models;
using AMS.DD35.Common.Data;

namespace AMS.DD35.WebMVC3
{
    public static class ExtensionMethods
    {
        public static SelectListItem ToSelectListItem<K, V>(this KeyValuePair<K, V> me)
        {
            SelectListItem item = new SelectListItem();
            item.Text = me.Value.ToString();
            item.Value = me.Key.ToString();
            return item;
        }

        public static IEnumerable<SelectListItem> ToSelectListItems<K, V>(this IDictionary<K, V> me)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (KeyValuePair<K, V> pair in me.AsEnumerable())
            {
                items.Add(pair.ToSelectListItem());
            }
            return items;
        }

        public static IEnumerable<SelectListItem> ToSelectListItems<K, V>(this IDictionary<K, V> me, K selectedValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (KeyValuePair<K, V> pair in me.AsEnumerable())
            {
                SelectListItem item = pair.ToSelectListItem();
                item.Selected = pair.Value.Equals(selectedValue) || pair.Key.Equals(selectedValue);
                items.Add(item);
            }
            return items;
        }

        public static SelectList ToSelectList<K, V>(this IDictionary<K, V> me)
        {
            return new SelectList(me.ToSelectListItems<K, V>(), "Value", "Text", "");
        }

        public static SelectList ToSelectList<K, V>(this IDictionary<K, V> me, K selectedValue)
        {
            //return new SelectList(me.ToSelectListItems<K, V>(), "Key", "Value", selectedValue);
            return new SelectList(me.ToSelectListItems<K, V>(selectedValue), "Value", "Text", selectedValue);
        }
    }
}